<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option label="启用" :value="0" />
          <el-option label="禁用" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['system:salesperson:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:salesperson:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['system:salesperson:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="主键id" align="center" prop="id" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="手机号" align="center" prop="mobile" />
      <el-table-column label="推广码" align="center" prop="promoteCode">
        <template #default="scope">
          <el-image
            v-if="scope.row.promoteCode"
            :src="scope.row.promoteCode"
            :preview-src-list="[scope.row.promoteCode]"
            :initial-index="0"
            fit="cover"
            style="width: 60px; height: 60px"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column label="推广数量" align="center" prop="outletCount" />
      <el-table-column label="推广明细" align="center" width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openOutletDialog(scope.row)"
            v-hasPermi="['system:salesperson:query']"
          >
            查看明细
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
            {{ scope.row.status === 0 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="200px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['system:salesperson:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            :type="scope.row.status === 0 ? 'warning' : 'success'"
            @click="handleFreeze(scope.row)"
            v-hasPermi="['system:salesperson:update']"
          >
            {{ scope.row.status === 0 ? '冻结' : '解冻' }}
          </el-button>
          <el-button
            link
            type="primary"
            @click="openResetPasswordDialog(scope.row)"
            v-hasPermi="['system:salesperson:updatepassword']"
          >
            重置密码
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['system:salesperson:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <SalespersonForm ref="formRef" @success="getList" />

  <!-- 推广明细弹窗 -->
  <Dialog title="推广明细" v-model="outletDialogVisible" width="1200px">
    <el-table v-loading="outletLoading" :data="outletList" :stripe="true">
      <el-table-column label="门店ID" align="center" prop="id" width="80px" />
      <el-table-column label="门店名称" align="center" prop="name" min-width="120px" />
      <el-table-column label="门店门头照" align="center" prop="headImage" width="100px">
        <template #default="scope">
          <el-image
            v-if="scope.row.headImage"
            :src="scope.row.headImage"
            :preview-src-list="[scope.row.headImage]"
            :initial-index="0"
            fit="cover"
            style="width: 50px; height: 50px"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column label="门店负责人" align="center" prop="owner" width="100px" />
      <el-table-column label="手机号" align="center" prop="mobile" width="120px" />
      <!-- <el-table-column label="微信号" align="center" prop="wxNumber" width="120px" /> -->
      <el-table-column
        label="详细地址"
        align="center"
        prop="detailAddress"
        min-width="200px"
        show-overflow-tooltip
      />
      <el-table-column
        label="推广时间"
        align="center"
        prop="promoteTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <!-- <el-table-column
        label="过期时间"
        align="center"
        prop="expireTime"
        :formatter="dateFormatter"
        width="180px"
      /> -->
      <el-table-column label="是否已存档" align="center" prop="archive" width="100px">
        <template #default="scope">
          <el-tag :type="scope.row.archive === 1 ? 'success' : 'info'">
            {{ scope.row.archive === 1 ? '已存档' : '未存档' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="outletTotal"
      v-model:page="outletQueryParams.pageNo"
      v-model:limit="outletQueryParams.pageSize"
      @pagination="getOutletList"
    />
  </Dialog>

  <!-- 重置密码弹窗 -->
  <Dialog title="重置密码" v-model="resetPasswordDialogVisible" width="400px">
    <el-form
      ref="resetPasswordFormRef"
      :model="resetPasswordForm"
      :rules="resetPasswordRules"
      label-width="80px"
    >
      <el-form-item label="业务员" prop="name">
        <el-input v-model="resetPasswordForm.name" disabled />
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input
          v-model="resetPasswordForm.password"
          type="password"
          placeholder="请输入新密码（4-16位）"
          show-password
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="resetPasswordDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleResetPassword" :loading="resetPasswordLoading">
        确 定
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { SalespersonApi, SalespersonVO, OutletVO } from '@/api/system/salesperson'
import SalespersonForm from './SalespersonForm.vue'

/** 业务员 列表 */
defineOptions({ name: 'Salesperson' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<SalespersonVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  mobile: undefined,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SalespersonApi.getSalespersonPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 冻结/解冻按钮操作 */
const handleFreeze = async (row: SalespersonVO) => {
  try {
    const statusText = row.status === 0 ? '冻结' : '解冻'
    await message.confirm(`确认要${statusText}业务员"${row.name}"吗？`)
    // 调用修改接口，切换状态
    await SalespersonApi.updateSalesperson({
      ...row,
      status: row.status === 0 ? 1 : 0
    })
    message.success(`${statusText}成功`)
    // 刷新列表
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SalespersonApi.deleteSalesperson(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除业务员 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 批量删除
    await Promise.all(checkedIds.value.map((id) => SalespersonApi.deleteSalesperson(id)))
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: SalespersonVO[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SalespersonApi.exportSalesperson(queryParams)
    download.excel(data, '业务员.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 推广明细相关 */
const outletDialogVisible = ref(false)
const outletLoading = ref(false)
const outletList = ref<OutletVO[]>([])
const outletTotal = ref(0)
const outletQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  salespersonId: undefined as number | undefined
})

/** 打开推广明细弹窗 */
const openOutletDialog = (row: SalespersonVO) => {
  outletQueryParams.salespersonId = row.id
  outletQueryParams.pageNo = 1
  outletDialogVisible.value = true
  getOutletList()
}

/** 获取门店列表 */
const getOutletList = async () => {
  outletLoading.value = true
  try {
    const data = await SalespersonApi.getSalespersonOutlets(outletQueryParams)
    outletList.value = data.list
    outletTotal.value = data.total
  } finally {
    outletLoading.value = false
  }
}

/** 重置密码相关 */
const resetPasswordDialogVisible = ref(false)
const resetPasswordLoading = ref(false)
const resetPasswordFormRef = ref()
const resetPasswordForm = ref<{
  id: number | undefined
  name: string
  password: string
}>({
  id: undefined,
  name: '',
  password: ''
})
const resetPasswordRules = reactive({
  password: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    { min: 4, max: 16, message: '密码长度为 4-16 位', trigger: 'blur' }
  ]
})

/** 打开重置密码弹窗 */
const openResetPasswordDialog = (row: SalespersonVO) => {
  resetPasswordForm.value = {
    id: row.id,
    name: row.name,
    password: ''
  }
  resetPasswordDialogVisible.value = true
  // 清空表单验证
  nextTick(() => {
    resetPasswordFormRef.value?.clearValidate()
  })
}

/** 重置密码 */
const handleResetPassword = async () => {
  try {
    // 校验表单
    await resetPasswordFormRef.value.validate()
    // 二次确认
    await message.confirm(`确认要重置业务员"${resetPasswordForm.value.name}"的密码吗？`)
    // 提交请求
    resetPasswordLoading.value = true
    await SalespersonApi.updateSalespersonPassword(
      resetPasswordForm.value.id!,
      resetPasswordForm.value.password
    )
    message.success('重置密码成功')
    resetPasswordDialogVisible.value = false
  } catch {
  } finally {
    resetPasswordLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
